/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import {
  Form,
  Input,
  InputNumber,
  Radio,
  TreeSelect,
  Select,
  Collapse,
  Button,
  message,
  Card,
  Icon,
  Cascader,
  Col,
  Tooltip, DatePicker,
} from 'antd';
import {connect} from 'dva';
import request from '@/utils/request';
import Highlighter from "react-highlight-words";
import moment from 'moment';

const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const Panel = Collapse.Panel;
let uuid=5;
class EditUserArchives extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meterArr: [1, 2, 3, 4,5],
      meterActiveKey: ['1', '2', '3', '4', '5'],
      meter1: [],
      meter2: [],
      meter3: [],
      meter4: [],
      all_materials:[],
      all_warehouses:[]
    };
  }


  componentDidMount() {
    const that=this;
    request(`/all_materials`, {
      method: 'GET',

    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_materials: response.data.data,
        });
      }

    });
    request(`/all_warehouses`, {
      method: 'GET',

    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_warehouses: response.data.data,
        });
      }

    });
  }

  addMeter = () => {
    uuid++;
    this.state.meterArr.push(uuid);
    this.state.meterActiveKey.push(uuid.toString());
    this.setState({
      [`meter${uuid}`]: [],
      meterArr: this.state.meterArr,
      meterActiveKey: this.state.meterActiveKey,
    });
  };
  deleteMeter = (item) => {
    console.log('删除的item', item);
    if (this.state.meterArr.length === 1) {
      console.log('只有一个水表');
      // message.error('至少需要一个水表')
      // return false
    }
    const index = this.state.meterArr.indexOf(item);
    console.log('index', index);
    this.state.meterArr.splice(index, 1);
    this.setState({
      meterArr: this.state.meterArr,
    });
  };
  handleCascader= (type,value, item) => {
    console.log(value);
    const {
      form
    } = this.props;
    const that = this;
    form.validateFields((err, fieldsValue) => {
      console.log('fieldsValue',fieldsValue)
      let searchParams={}
      if(type==='warehouse_area_id'){
        searchParams={
          warehouse_area_id:value[value.length-1],
          material_id:fieldsValue[`material_id-${item}`]
        }
      }else if(type==='material_id'){
        searchParams={
          warehouse_area_id:fieldsValue[`warehouse_area_id-${item}`]?fieldsValue[`warehouse_area_id-${item}`][fieldsValue[`warehouse_area_id-${item}`].length-1]:'',
          material_id:value
        }
      }
      console.log('searchParams',searchParams)
      request(`/all_inventories`, {
        method: 'GET',
        params:searchParams
      }).then((response) => {
        console.log(response)
        console.log('设置item',item)
        if (response.status === 200) {
          if(response.data.data.length>0){
            that.props.form.setFieldsValue({
              [`save_count-${item}`]: response.data.data[0].count,
            });
          }else{
            that.props.form.setFieldsValue({
              [`save_count-${item}`]:0,
            });
          }

        }
      });
    });

  }
  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 18},
      }
    };
    const {getFieldDecorator, getFieldValue} = this.props.form;

    const meterForms=this.state.meterArr.map((item, index) => {
      return (
        <Form style={{ display: 'flex' }} className={'custom-table-form'} key={index} layout="inline">
          <div style={{ width: '50px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            {index + 1}
          </div>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`warehouse_area_id-${item}`, {
              initialValue: '',
            })(
              <Cascader
                onChange={(value) => this.handleCascader('warehouse_area_id',value, `${item}`)}
                fieldNames={{children:'warehouse_areas',label: 'name', value: 'id'}}
                style={{width:'172px'}}
                options={this.state.all_warehouses} />
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`material_id-${item}`, {
              initialValue: '',
            })(
              <Select
                style={{width:'172px'}}
                filterOption={false}
                notFoundContent={null}
                onChange={(value) => this.handleCascader('material_id',value, `${item}`)}
              >
                {this.state.all_materials.map((item, index2) => {
                  return <Option key={index2} value={item.id}>{item.name}</Option>;
                })}
              </Select>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`save_count-${item}`, {
              initialValue: '',
            })(
              <Input disabled={true} style={{ width: '172px', fontWeight: 'bold' }}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`actual_count-${item}`, {
              initialValue: '',
            })(
              <Input style={{ width: '100%', fontWeight: 'bold' }}/>,
            )}
          </FormItem>
          <div style={{ width: '80px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            <Button
              style={{ height: '22px' }}
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                e.stopPropagation();
                this.deleteMeter(item);
              }
              }
            >删除
            </Button>
          </div>


        </Form>
      );
    });
    return (
      <div>

        <Collapse activeKey={['1','2']} >
          <Panel header={'盘点单基本信息'} key="1" showArrow={false}>
            <Form onSubmit={this.handleSubmit}>
              <FormItem
                label={'备注'}
                {...formItemLayoutWithLabel}
              >
                {getFieldDecorator('remark', {
                  initialValue: this.props.editRecord? this.props.editRecord.remark:'',
                })(
                  <Input />
                )}
              </FormItem>

            </Form>
          </Panel>
          <Panel header={'选择盘点材料'} key="2" showArrow={false} >
            <div style={{ border: '1px solid #d9d9d9', marginTop: '10px' }}>

              <div style={{
                display: 'flex',
                fontWeight: 'bold',
                lineHeight: '32px',
                height: '32px',
                background: 'rgb(249,249,249)',
              }}>
                <div style={{ width: '50px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>序号</div>
                <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>盘点区域</div>
                <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>盘点材料</div>
                <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>库存数量</div>
                <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>盘点数量</div>
                <div style={{ width: '80px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>操作</div>
              </div>
              {meterForms}
              <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addMeter}>添加行</Button>

            </div>
          </Panel>
        </Collapse>
      </div>
    );
  }
}

const EditUserArchivesFormWrap = Form.create()(EditUserArchives);
export default connect()(EditUserArchivesFormWrap);
